package br.furb.jpa;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class GenericDao<Model> {
	
	private EntityManager entityManager;
	
	public GenericDao(String persistenceUnit) {
		entityManager = Persistence
				.createEntityManagerFactory(persistenceUnit)
				.createEntityManager();
	}

	public void delete(Model model) {
		EntityTransaction transaction = entityManager.getTransaction();
		try {
			transaction.begin();
			model = updateDetached(model);
			entityManager.remove(model);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		}
	}
	
	public Model findById(Serializable id, Class<Model> clazz) {
		return (Model)entityManager.find(clazz, id);		
	}
	
	public Model save(Model model) {
		EntityTransaction transaction = entityManager.getTransaction();
		try {
			transaction.begin();
			model = entityManager.merge(model);
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		}
		return model;
	}
	
	public Model updateDetached(Model model){
		return entityManager.merge(model);
	}
	
	@SuppressWarnings("unchecked")
	public List<Model> getAllModels(Class<Model> clazz) {
		Query query = entityManager.createQuery("SELECT o FROM " + clazz.getSimpleName() + " o ");	
		return query.getResultList();
	}
	
}
